<script setup>
import SearchForm from '@/components/Search-Form.vue'
import { ref } from 'vue'
import {
    addBuildingItem,
    delBuildingItem,
    editBuildingItem,
    getBuildingItem,
    getBuildingList
} from '@/api/building'
import TableBase from '@/components/Table-Base.vue'
import TablePagination from '@/components/Table-Pagination.vue'
import DialogBase from '@/components/Dialog-Base.vue'
import { MessagePlugin } from 'tdesign-vue-next'
import MainContent from '@/components/Main-Content.vue'

const showDialog = ref(false)
const dialogType = ref('add')
const rules = ref({
    name: [
        { required: true, message: '请输入楼宇名称', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ],
    floors: [
        { required: true, message: '请输入楼宇层数', trigger: 'blur' },
        { min: 1, message: '楼宇层数最少为 1', trigger: 'blur' }
    ],
    area: [
        { required: true, message: '请输入在管面积', trigger: 'blur' },
        { min: 1, message: '在管面积最少为 1', trigger: 'blur' }
    ],
    propertyFeePrice: [
        { required: true, message: '请输入物业费', trigger: 'blur' },
    ]
})
const dialogForm = ref({})
const formData = ref({
    name: ''
})
const query = ref({
    page: 1,
    pageSize: 10
})
const listData = ref({
    list: [],
    total: 0
})
const columns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '楼宇名称',
        colKey: 'name'
    },
    {
        title: '楼宇层数',
        colKey: 'floors'
    },
    {
        title: '在管面积（㎡）',
        colKey: 'area'
    },
    {
        title: '物业费（元/㎡）',
        colKey: 'propertyFeePrice'
    },
    {
        title: '状态',
        colKey: 'status'
    },
    {
        title: '操作',
        colKey: 'option'
    }
])
const dialogFormInstance = ref(null)

const search = async () => {
    const res = await getBuildingList({
        ...query.value,
        ...formData.value
    })
    listData.value.list = res.data.rows.map(e => {
        e.status === 1 ? e.status = '租赁中' : e.status = '空置中'
        return e
    })
    listData.value.total = res.data.total
}
const reset = () => {
    formData.value.name = ''
    search()
}
const addBuilding = () => {
    dialogType.value = 'add'
    showDialog.value = true
}
const closeDialog = () => {
    showDialog.value = false
    dialogFormInstance.value.clearValidate()
}
const clickClose = () => {
    showDialog.value = false
    dialogFormInstance.value.reset()
}
const dialogConfirm = async () => {
    const valid = await dialogFormInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        if (dialogType.value === 'add') {
            const res = await addBuildingItem(dialogForm.value)
            if (res.code !== 10000) return
            closeDialog()
            dialogFormInstance.value.reset()
            await MessagePlugin.success('添加成功！')
            await search()
        } else {
            const res = await editBuildingItem({
                id: dialogForm.value.id,
                name: dialogForm.value.name,
                floors: dialogForm.value.floors,
                area: dialogForm.value.area,
                propertyFeePrice: dialogForm.value.propertyFeePrice
            })
            if (res.code !== 10000) return
            closeDialog()
            await MessagePlugin.success('修改成功！')
            await search()
        }
    }
}
const getRow = async (data, type) => {
    if (type === 'edit') {
        dialogType.value = 'edit'
        showDialog.value = true
        const res = await  getBuildingItem(data.row.id)
        if (res.code === 10000) dialogForm.value = res.data
    } else {
        const res = await delBuildingItem(data.row.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            if (listData.value.list.length === 1 && query.value.page > 1) query.value.page--
            await search()
        } else {
            await MessagePlugin.error(res.msg)
        }
    }
}
const changePage = e => {
    query.value.page = e.current
    query.value.pageSize = e.pageSize
    search()
}

search()
</script>

<template>
    <main-content>
        <search-form>
            <t-form
                ref="form"
                :data="formData"
                label-width="auto"
                layout="inline"
            >
                <t-form-item label="楼宇名称">
                    <t-input v-model.trim="formData.name" placeholder="请输入楼宇名称"></t-input>
                </t-form-item>

                <t-form-item style="min-width: auto">
                    <t-button @click="search" type="submit" style="margin-right: 10px;">查询</t-button>
                    <t-button @click="reset" variant="outline">重置</t-button>
                </t-form-item>
            </t-form>
        </search-form>

        <table-base :columns="columns" :list="listData.list">
            <template #top-btn>
                <t-button theme="primary" @click="addBuilding">添加楼宇</t-button>
            </template>
            <template #option-table="row">
                <t-button variant="text" theme="primary" @click="getRow(row, 'edit')">编辑</t-button>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'del')"
                    theme="warning" content="确认删除吗">
                    <t-button variant="text" theme="primary">删除</t-button>
                </t-popconfirm>
            </template>
        </table-base>

        <table-pagination :total="listData.total" @changePage="changePage"></table-pagination>

        <dialog-base :showDialog="showDialog"
                     :dialogType="dialogType"
                     :dialogTitle="dialogType === 'add' ? '添加楼宇' : '编辑楼宇'"
                     @dialogConfirm="dialogConfirm"
                     @clickClose="clickClose"
                     @closeDialog="closeDialog">
            <t-form class="dialogForm" ref="dialogFormInstance" labelAlign="top" :rules="rules" :data="dialogForm">
                <t-form-item label="楼宇名称" name="name">
                    <t-input placeholder="请输入楼宇名称" v-model.trim="dialogForm.name"/>
                </t-form-item>
                <t-form-item label="楼宇层数" name="floors">
                    <t-input-number placeholder="请输入楼宇层数"
                                    v-model.trim="dialogForm.floors"
                                    theme="column" min="1" max="20" :allowInputOverLimit="false"/>
                </t-form-item>
                <t-form-item label="在管面积" name="area">
                    <t-input-adornment append="㎡">
                        <t-input-number placeholder="请输入在管面积"
                                        v-model.trim="dialogForm.area"
                                        theme="column" min="1" max="100000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>
                <t-form-item label="物业费" name="propertyFeePrice">
                    <t-input-adornment append="元/㎡">
                        <t-input-number placeholder="请输入物业费"
                                        v-model.trim="dialogForm.propertyFeePrice"
                                        theme="column" min="0" max="1000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>
            </t-form>
        </dialog-base>
    </main-content>
</template>

<style scoped lang="scss">
.dialogForm {
    :deep .t-form__controls-content {
        .t-input-number {
            flex: 1;
            width: initial;
        }

        .t-input-adornment {
            flex: 1;

            .t-input-number {
                flex: 1;
                width: auto;
            }
        }
    }

    :deep .t-form-item__propertyFeePrice {
        .t-input-adornment__text {
            width: 52px;
        }
    }
}
</style>
